<?php

namespace app\v6\controller;

use app\service\AliSmsService;
use app\service\EmailService;
use app\service\JwtService;
use app\service\WechatService;
use think\Db;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Lang;

class Login
{
    /**
     * 用户登录
     * 支持手机号/邮箱 + 密码登录
     * 支持手机号 + 验证码登录.
     */
    public function login()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        $loginType = input('login_type', 'password'); // password或code
        $account = input('phone', ''); // 手机号或邮箱

        if (empty($account)) {
            $result['code'] = 1;
            $result['msg'] = '账号不能为空';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($account, FILTER_VALIDATE_EMAIL) ? true : false;
        $field = $isEmail ? 'email' : 'phone';

        // 查询用户
        $user = Db::name('member')->where([$field => $account])->find();
        
        // 密码登录
        if ($loginType === 'password') {
            // 密码登录必须用户存在
            if (!$user) {
                $result['code'] = 1;
                $result['msg'] = Lang::get('user_not_exist_please_register');

                return json($result);
            }

            $password = input('password', '');
            if (empty($password)) {
                $result['code'] = 1;
                $result['msg'] = Lang::get('password_required');

                return json($result);
            }

            // 验证密码
            if (!password_verify($password, $user['password'])) {
                $result['code'] = 1;
                $result['msg'] = Lang::get('password_error');

                return json($result);
            }
        }
        // 验证码登录
        elseif ($loginType === 'code') {
            $code = input('code', '');
            if (empty($code)) {
                $result['code'] = 1;
                $result['msg'] = Lang::get('verification_code_required');

                return json($result);
            }

            // 验证验证码
            $cachedCode = Cache::get($account);
            if (!$cachedCode || $cachedCode != $code) {
                $result['code'] = 1;
                $result['msg'] = Lang::get('verification_code_error_or_expired');

                return json($result);
            }

            // 验证成功后删除缓存的验证码
            Cache::rm($account);

            // 如果用户不存在，则自动注册
            if (!$user) {
                $password = rand(100000, 999999);
                // 准备用户数据
                $userData = [
                    'agent_id' => 0,
                    'phone' => $isEmail ? '' : $account,
                    'email' => $isEmail ? $account : '',
                    'openid' => '',
                    'password' => password_hash($password, PASSWORD_DEFAULT),
                    'create_time' => time(),
                    'sex' => 0,
                    'birth' => '',
                    'once_nums' => 0,
                    'month_day' => 0,
                    'works_once_nums' => 0,
                    'works_month_nums' => 0,
                    'emotion_once_nums' => 0,
                    'emotion_month_nums' => 0,
                    'pr_once_nums' => 0,
                    'pr_month_nums' => 0,
                    'group_once_nums' => 0,
                    'group_month_nums' => 0,
                    'stu_once_nums' => 0,
                    'stu_month_nums' => 0,
                    'uid' => 0,
                    'medical_once_nums' => 0,
                    'free_nums' => 2,
                ];
                
                // 插入新用户
                $userId = Db::name('member')->insertGetId($userData);
                if (!$userId) {
                    $result['code'] = 1;
                    $result['msg'] = Lang::get('register_failed');

                    return json($result);
                }

                // 重新查询用户信息
                $user = Db::name('member')->where('id', $userId)->find();
            }
        } else {
            $result['code'] = 1;
            $result['msg'] = Lang::get('login_method_not_supported');

            return json($result);
        }

        // 生成JWT令牌
        $payload = [
            'id' => $user['id'],
            'phone' => $user['phone'],
            'email' => $user['email'],
        ];
        $token = JwtService::createToken($payload, config('app.jwt_expire'));

        // 返回用户信息和令牌
        unset($user['password']); // 移除密码字段
        $user['nickname'] = $user['phone'] ?? $user['email'];
        $result['data'] = [
            'user' => $user,
            'token' => $token,
        ];
        $result['msg'] = '登录成功';

        return json($result);
    }

    /**
     * 用户注册
     * 支持手机号/邮箱注册.
     */
    public function register()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        $account = input('account', ''); // 手机号或邮箱
        $code = input('code', '');
        $password = input('password', '');

        if (empty($account)) {
            $result['code'] = 1;
            $result['msg'] = '账号不能为空';

            return json($result);
        }

        if (empty($code)) {
            $result['code'] = 1;
            $result['msg'] = '验证码不能为空';

            return json($result);
        }

        if (empty($password)) {
            $result['code'] = 1;
            $result['msg'] = '密码不能为空';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($account, FILTER_VALIDATE_EMAIL) ? true : false;
        $field = $isEmail ? 'email' : 'phone';

        // 验证验证码
        $cachedCode = Cache::get($account);
        if (!$cachedCode || $cachedCode != $code) {
            $result['code'] = 1;
            $result['msg'] = '验证码错误或已过期';

            return json($result);
        }

        // 检查用户是否已存在
        $exists = Db::name('member')->where([$field => $account])->find();
        if ($exists) {
            $result['code'] = 1;
            $result['msg'] = '该账号已注册';

            return json($result);
        }

        // 准备用户数据
        $userData = [
            'agent_id' => 0,
            'phone' => $isEmail ? '' : $account,
            'email' => $isEmail ? $account : '',
            'openid' => '',
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'create_time' => time(),
            'sex' => 0,
            'birth' => '',
            'once_nums' => 0,
            'month_day' => 0,
            'works_once_nums' => 0,
            'works_month_nums' => 0,
            'emotion_once_nums' => 0,
            'emotion_month_nums' => 0,
            'pr_once_nums' => 0,
            'pr_month_nums' => 0,
            'group_once_nums' => 0,
            'group_month_nums' => 0,
            'stu_once_nums' => 0,
            'stu_month_nums' => 0,
            'uid' => 0,
            'medical_once_nums' => 0,
            'free_nums' => 2,
        ];

        // 添加用户
        $userId = Db::name('member')->insertGetId($userData);
        if (!$userId) {
            $result['code'] = 1;
            $result['msg'] = '注册失败，请重试';

            return json($result);
        }

        // 删除缓存的验证码
        Cache::rm($account);

        // 生成JWT令牌
        $payload = [
            'id' => $userId,
            'phone' => $userData['phone'],
            'email' => $userData['email'],
        ];
        $token = JwtService::createToken($payload, config('app.jwt_expire'));

        // 返回用户信息和令牌
        $userData['id'] = $userId;
        unset($userData['password']); // 移除密码字段
        $result['data'] = [
            'user' => $userData,
            'token' => $token,
        ];
        $result['msg'] = '注册成功';

        return json($result);
    }

    /**
     * 用户退出登录.
     */
    public function logout()
    {
        try {
            // 获取当前用户
            $user_id = getUserId();
            $user = Db::name('member')->where('id', $user_id)->find();

            if ($user && !empty($user['openid'])) {
                // 如果是微信用户，清理相关缓存
                // 查找所有与该用户相关的微信登录缓存

                // 日志记录退出登录
                Log::record('微信用户退出登录，清理缓存: '.$user['openid'], 'notice');

                // 清理可能存在的缓存
                $cacheKeys = Cache::getCacheKeys('wechat_login_*');
                foreach ($cacheKeys as $key) {
                    Cache::rm($key);
                }
            }
        } catch (\Exception $e) {
            Log::error('退出登录时清理缓存异常：'.$e->getMessage());
        }

        // JWT无需在服务端处理退出登录，客户端删除token即可
        return json(['code' => 0, 'data' => [], 'msg' => '退出成功']);
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        // 获取JWT令牌中的用户ID
        $token = JwtService::getTokenFromHeader();
        if (!$token) {
            $result['code'] = 401;
            $result['msg'] = '请先登录';

            return json($result);
        }

        $payload = JwtService::verifyToken($token);
        if (!$payload) {
            $result['code'] = 401;
            $result['msg'] = '登录已过期，请重新登录';

            return json($result);
        }

        $userId = $payload['id'];
        $oldPassword = input('old_password', '');
        $newPassword = input('new_password', '');

        if (empty($oldPassword) || empty($newPassword)) {
            $result['code'] = 1;
            $result['msg'] = '原密码和新密码不能为空';

            return json($result);
        }

        // 验证原密码
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            $result['code'] = 1;
            $result['msg'] = '用户不存在';

            return json($result);
        }

        if (!password_verify($oldPassword, $user['password'])) {
            $result['code'] = 1;
            $result['msg'] = '原密码错误';

            return json($result);
        }

        // 更新密码
        $update = Db::name('member')->where(['id' => $userId])->update([
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
        ]);

        if (!$update) {
            $result['code'] = 1;
            $result['msg'] = '密码修改失败，请重试';

            return json($result);
        }

        $result['msg'] = '密码修改成功';

        return json($result);
    }

    /**
     * 获取微信登录授权URL
     * 返回用于微信登录的授权URL.
     */
    public function wechatLogin()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        try {
            // 生成state参数，用于防止CSRF攻击
            $state = md5(uniqid(mt_rand(), true));
            // 缓存state，用于后续验证，有效期10分钟
            Cache::set('wechat_state_'.$state, 1, 600);

            // 检测是否是微信浏览器
            $userAgent = request()->header('user-agent');
            $isWechat = false;
            if (stripos($userAgent, 'MicroMessenger') !== false) {
                $isWechat = true;
                Log::info('检测到微信内置浏览器访问');
            }

            // 检测是否是移动设备
            $isMobile = false;
            if (stripos($userAgent, 'Mobile') !== false || stripos($userAgent, 'Android') !== false || stripos($userAgent, 'iPhone') !== false) {
                $isMobile = true;
            }

            // 获取微信登录授权URL，传递设备类型信息
            $url = WechatService::getAuthUrl($state, $isWechat, $isMobile);

            if (empty($url)) {
                $result['code'] = 1;
                $result['msg'] = '获取微信登录链接失败';

                return json($result);
            }

            $result['data']['url'] = $url;
            $result['data']['is_wechat'] = $isWechat; // 返回给前端，便于判断
            $result['data']['is_mobile'] = $isMobile; // 返回给前端，便于判断
            $result['msg'] = '获取微信登录链接成功';
        } catch (\Exception $e) {
            Log::error('获取微信登录授权链接异常：'.$e->getMessage());
            $result['code'] = 1;
            $result['msg'] = '系统异常，请稍后再试';
        }

        return json($result);
    }

    /**
     * 微信登录回调处理
     * 处理微信授权后的回调请求，获取用户信息并完成登录.
     */
    public function wechatCallback()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        try {
            $code = input('code', '');
            $state = input('state', '');

            // 验证state，防止CSRF攻击
            $stateData = Cache::get('wechat_state_'.$state);
            if (!$stateData) {
                return $this->showErrorPage('无效的请求', $state);
            }

            // 检查是否已经处理过此state（防止重复处理）
            if (Cache::get('wechat_processed_'.$state)) {
                Log::info('微信登录state已处理过，跳过重复请求: '.$state);
                return $this->showErrorPage('请求已处理，请勿重复操作', $state);
            }

            // 标记此state为正在处理（而不是立即删除）
            Cache::set('wechat_processed_'.$state, time(), 600); // 10分钟过期

            if (empty($code)) {
                return $this->showErrorPage('授权失败，请重试', $state);
            }

            // 检测是否是微信浏览器和移动设备
            $userAgent = request()->header('user-agent');
            $isWechat = false;
            $isMobile = false;

            // 检测是否是微信内置浏览器
            if (stripos($userAgent, 'MicroMessenger') !== false) {
                $isWechat = true;
                Log::info('回调中检测到微信内置浏览器访问');
            }

            // 检测是否是移动设备
            if (stripos($userAgent, 'Mobile') !== false || stripos($userAgent, 'Android') !== false || stripos($userAgent, 'iPhone') !== false) {
                $isMobile = true;
                Log::info('回调中检测到移动设备访问');
            }

            // 记录设备环境日志
            $deviceInfo = [
                'isWechat' => $isWechat,
                'isMobile' => $isMobile,
            ];
            Log::info('微信回调设备信息: '.json_encode($deviceInfo));

            // 通过code获取access_token，传递设备类型信息
            $tokenInfo = WechatService::getAccessToken($code, $isWechat, $isMobile);
            if (empty($tokenInfo) || isset($tokenInfo['errcode'])) {
                $errMsg = isset($tokenInfo['errmsg']) ? $tokenInfo['errmsg'] : '获取微信访问令牌失败';
                Log::error('微信登录获取access_token失败：'.json_encode($tokenInfo, JSON_UNESCAPED_UNICODE));

                return $this->showErrorPage($errMsg, $state);
            }

            // 获取用户信息
            $userInfo = WechatService::getUserInfo($tokenInfo['access_token'], $tokenInfo['openid']);
            if (empty($userInfo) || isset($userInfo['errcode'])) {
                $errMsg = isset($userInfo['errmsg']) ? $userInfo['errmsg'] : '获取微信用户信息失败';
                Log::error('微信登录获取用户信息失败：'.json_encode($userInfo, JSON_UNESCAPED_UNICODE));

                return $this->showErrorPage($errMsg, $state);
            }

            // 处理用户登录
            $userResult = $this->handleWechatUser($userInfo);

            if ($userResult['code'] != 0) {
                return $this->showErrorPage($userResult['msg'], $state);
            }

            $result['data'] = $userResult['data'];
            $result['msg'] = '登录成功';

            // 【关键】提前设置缓存，确保前端轮询时能立即获取到登录结果
            // 在显示页面或重定向之前就设置好缓存，避免时序问题
            Cache::set('wechat_login_'.$state, $result, 300); // 缓存5分钟
            
            Log::info('微信登录成功，已设置缓存: wechat_login_'.$state);

            // 区分处理：微信内置浏览器重定向，其他浏览器显示成功页面
            if ($isWechat && $isMobile) {
                // 微信内置浏览器：直接重定向回应用（因为无法关闭窗口）
                // 使用前端域名，而不是后端API域名
                $frontendDomain = \think\facade\Env::get('app.frontendDomain', '');
                if (empty($frontendDomain)) {
                    // 如果没有配置前端域名，使用当前请求的域名
                    $frontendDomain = request()->domain();
                }
                $returnUrl = rtrim($frontendDomain, '/').'/#/chat/home';
                Log::info('移动端微信浏览器，重定向到: '.$returnUrl);
                
                // 使用HTML重定向，确保可靠
                $html = <<<EOT
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录成功</title>
    <style>
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f8f8f8;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            padding: 40px;
            max-width: 400px;
            width: 80%;
        }
        .success-icon {
            color: #07c160;
            font-size: 60px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }
        p {
            color: #666;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="success-icon">✓</div>
        <h1>登录成功</h1>
        <p id="message">正在返回... <span id="countdown">3</span>秒</p>
        <button id="manualBtn" style="display:none; margin-top: 20px; padding: 10px 30px; background: #07c160; color: white; border: none; border-radius: 4px; font-size: 16px;">点击返回</button>
    </div>
    <script>
        var returnUrl = '{$returnUrl}';
        var countdown = 3;
        var countdownEl = document.getElementById('countdown');
        var messageEl = document.getElementById('message');
        var manualBtn = document.getElementById('manualBtn');
        
        // 倒计时
        var timer = setInterval(function() {
            countdown--;
            if (countdownEl) countdownEl.textContent = countdown;
            if (countdown <= 0) {
                clearInterval(timer);
                doRedirect();
            }
        }, 1000);
        
        // 执行跳转
        function doRedirect() {
            try {
                // 方式1: location.href（最常用）
                window.location.href = returnUrl;
                
                // 方式2: 如果1秒后还没跳转，尝试 replace
                setTimeout(function() {
                    window.location.replace(returnUrl);
                }, 1000);
                
                // 方式3: 如果2秒后还没跳转，显示手动按钮
                setTimeout(function() {
                    if (messageEl) messageEl.textContent = '自动跳转失败，请点击按钮返回';
                    if (manualBtn) {
                        manualBtn.style.display = 'block';
                        manualBtn.onclick = function() {
                            window.location.href = returnUrl;
                        };
                    }
                }, 2000);
            } catch(e) {
                console.error('跳转失败:', e);
                if (messageEl) messageEl.textContent = '跳转失败，请点击按钮返回';
                if (manualBtn) {
                    manualBtn.style.display = 'block';
                    manualBtn.onclick = function() {
                        window.location.href = returnUrl;
                    };
                }
            }
        }
    </script>
</body>
</html>
EOT;
                return response($html);
            } else {
                // PC端或其他浏览器：显示成功页面并自动关闭
                Log::info('PC端或其他浏览器，显示成功页面');
                return $this->showSuccessPage($userResult['data']['user']['nickname'] ?? '用户', false);
            }
        } catch (\Exception $e) {
            Log::error('微信登录回调处理异常：'.$e->getMessage());

            return $this->showErrorPage('系统异常，请稍后再试', $state);
        }
    }

    /**
     * 显示微信登录成功页面.
     *
     * @param string $nickname 用户昵称
     *
     * @return \think\Response
     */
    private function showSuccessPage($nickname, $isMobile = false)
    {
        // 统一处理：PC端和移动端都自动关闭窗口
        // 移动端倒计时稍短一些，提升体验
        $seconds = $isMobile ? 2 : 3;
        
        $html = <<<EOT
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信登录成功</title>
    <style>
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f8f8f8;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            padding: 40px;
            max-width: 400px;
            width: 80%;
        }
        .success-icon {
            color: #07c160;
            font-size: 60px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }
        p {
            color: #666;
            font-size: 16px;
            margin-bottom: 20px;
        }
        .countdown {
            font-weight: bold;
            color: #07c160;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="success-icon">✓</div>
        <h1>登录成功</h1>
        <p>欢迎回来，{$nickname}！</p>
        <p>窗口将在 <span class="countdown" id="countdown">{$seconds}</span> 秒后自动关闭...</p>
    </div>

    <script>
        // 倒计时关闭窗口
        let seconds = {$seconds};
        const countdownElement = document.getElementById('countdown');
        
        const timer = setInterval(() => {
            seconds--;
            countdownElement.textContent = seconds;
            
            if (seconds <= 0) {
                clearInterval(timer);
            }
        }, 1000);
        
        // 统一使用 window.close() 关闭窗口
        setTimeout(() => {
            window.close();
            // 如果无法关闭（某些浏览器限制），提示用户手动关闭
            setTimeout(() => {
                document.body.innerHTML = '<div class="container"><p>请手动关闭此窗口</p></div>';
            }, 500);
        }, {$seconds} * 1000);
    </script>
</body>
</html>
EOT;

        return response($html);
    }

    /**
     * 显示微信登录错误页面.
     *
     * @param string $errorMsg 错误信息
     * @param string $state    状态码，用于在缓存中设置错误状态
     *
     * @return \think\Response
     */
    private function showErrorPage($errorMsg, $state)
    {
        // 设置错误状态到缓存，让前端轮询可以获取
        if (!empty($state)) {
            $errorResult = [
                'code' => 1,
                'msg' => $errorMsg,
                'data' => [],
            ];
            Cache::set('wechat_login_'.$state, $errorResult, 300); // 缓存5分钟
        }

        $html = <<<EOT
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信登录失败</title>
    <style>
        body {
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #f8f8f8;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            padding: 40px;
            max-width: 400px;
            width: 80%;
        }
        .error-icon {
            color: #fa5151;
            font-size: 60px;
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }
        p {
            color: #666;
            font-size: 16px;
            margin-bottom: 20px;
        }
        .countdown {
            font-weight: bold;
            color: #fa5151;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="error-icon">×</div>
        <h1>登录失败</h1>
        <p>{$errorMsg}</p>
        <p>窗口将在 <span class="countdown" id="countdown">5</span> 秒后自动关闭...</p>
    </div>

    <script>
        // 倒计时关闭窗口
        let seconds = 5;
        const countdownElement = document.getElementById('countdown');
        
        const timer = setInterval(() => {
            seconds--;
            countdownElement.textContent = seconds;
            
            if (seconds <= 0) {
                clearInterval(timer);
                window.close();
            }
        }, 1000);
    </script>
</body>
</html>
EOT;

        return response($html);
    }

    /**
     * 处理微信用户登录
     * 查找或创建微信用户，并生成登录令牌.
     *
     * @param array $userInfo 微信用户信息
     *
     * @return array 处理结果
     */
    private function handleWechatUser($userInfo)
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        $openid = $userInfo['openid'];

        // 查找是否有匹配的用户
        $user = Db::name('member')->where(['openid' => $openid])->find();

        if (!$user) {
            // 创建新用户
            $userData = [
                'agent_id' => 0,
                'phone' => '',
                'email' => '',
                'openid' => $openid,
                'nickname' => $userInfo['nickname'] ?? '',
                'password' => password_hash(md5(uniqid(mt_rand(), true)), PASSWORD_DEFAULT), // 随机密码
                'create_time' => time(),
                'sex' => $userInfo['sex'] ?? 0,
                'birth' => '',
                'once_nums' => 0,
                'month_day' => 0,
                'works_once_nums' => 0,
                'works_month_nums' => 0,
                'emotion_once_nums' => 0,
                'emotion_month_nums' => 0,
                'pr_once_nums' => 0,
                'pr_month_nums' => 0,
                'group_once_nums' => 0,
                'group_month_nums' => 0,
                'stu_once_nums' => 0,
                'stu_month_nums' => 0,
                'uid' => 0,
                'medical_once_nums' => 0,
                'free_nums' => 2,
            ];

            $userId = Db::name('member')->insertGetId($userData);
            if (!$userId) {
                $result['code'] = 1;
                $result['msg'] = '创建用户失败';

                return $result;
            }

            $userData['id'] = $userId;
            $user = $userData;
        }

        // 生成JWT令牌
        $payload = [
            'id' => $user['id'],
            'openid' => $user['openid'],
            'phone' => $user['phone'],
            'email' => $user['email'],
        ];
        $token = JwtService::createToken($payload, config('app.jwt_expire'));

        // 返回用户信息和令牌
        unset($user['password']); // 移除密码字段
        $user['nickname'] = $user['nickname'] ?? ($user['phone'] ?? ($user['email'] ?? '微信用户'));
        $result['data'] = [
            'user' => $user,
            'token' => $token,
        ];

        return $result;
    }

    /**
     * 检查微信登录状态
     * 用于前端轮询检查用户是否已通过微信授权完成登录.
     */
    public function checkWechatLogin()
    {
        $result = [
            'code' => 2, // 默认code=2表示等待登录中
            'msg' => '等待微信登录',
            'data' => [],
        ];

        try {
            $state = input('state', '');

            if (empty($state)) {
                $result['code'] = 1;
                $result['msg'] = '参数错误';

                return json($result);
            }

            // 优先检查是否有登录成功或失败的信息
            $loginInfo = Cache::get('wechat_login_'.$state);
            if ($loginInfo) {
                // 找到登录结果（成功或失败），直接返回
                Log::info('微信登录状态检查：找到登录结果，state='.$state.', code='.$loginInfo['code']);
                return json($loginInfo);
            }

            // 检查state是否还有效（表示正在等待登录）
            if (Cache::get('wechat_state_'.$state)) {
                // state存在且未被处理，用户正在扫码登录中，继续等待
                Log::info('微信登录状态检查：等待登录中，state='.$state);
                return json($result); // 返回code=2，等待登录中
            }

            // state已失效，登录超时
            Log::record('微信登录状态检查：state='.$state.', 已超时或失效', 'notice');
            $result['code'] = 1;
            $result['msg'] = '登录已超时或失败，请重新尝试';
        } catch (\Exception $e) {
            Log::error('检查微信登录状态异常：'.$e->getMessage());
            $result['code'] = 1;
            $result['msg'] = '系统异常，请稍后再试';
        }

        return json($result);
    }

    /**
     * 发送验证码
     * 根据邮箱还是手机, 发送不同的验证码
     */
    public function sendSmsCode()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [
                'res' => '',
            ],
        ];

        $phone = input('phone', '');

        if (empty($phone)) {
            $result['code'] = 1;
            $result['msg'] = '手机号或邮箱不能为空!';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($phone, FILTER_VALIDATE_EMAIL) ? true : false;

        // 如果不是邮箱，则验证手机号格式
        if (!$isEmail && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $result['code'] = 1;
            $result['msg'] = '手机号格式不正确!';

            return json($result);
        }

        // 生成验证码
        $code = rand(100000, 999999);

        // 发送验证码
        if ($isEmail) {
            // 使用邮箱发送验证码
            $sendResult = EmailService::sendCode($phone, $code);
            if ($sendResult !== true) {
                $result['code'] = 1;
                $result['msg'] = '邮箱验证码发送失败: '.$sendResult;

                return json($result);
            }
        } else {
            // 使用阿里云短信发送验证码
            $aliSmsConfig = config('app.ali_sms');
            $args = [
                'phone' => $phone,
                'template' => $aliSmsConfig['regCodeTpl'],
                'params' => '{"code":"'.$code.'"}',
            ];

            $sendResult = AliSmsService::main($args);
            if ($sendResult !== true) {
                $result['code'] = 1;
                $result['msg'] = '短信验证码发送失败';

                return json($result);
            }
        }

        // 缓存验证码，有效期5分钟
        Cache::set($phone, $code, 300);

        // 检测当前手机号/邮箱是否存在
        $field = $isEmail ? 'email' : 'phone';
        $userId = Db::name('member')->where([$field => $phone])->column('id');

        $result['msg'] = '验证码发送成功';
        $result['data']['is_show'] = empty($userId) ? 1 : 0;

        return json($result);
    }
}
